<?php

namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;

class AutoInitMiddleware implements MiddlewareInterface
{

    public function process(Request $request, callable $next): Response
    {
        // 获取当前请求路径
        $path = trim(strtolower($request->path()), '/');
        $parts = array_values(array_filter(explode('/', $path)));
        $route = count($parts) >= 3 ? implode('/', array_slice($parts, -3)) : implode('/', $parts);

        // 获取 token 和用户信息
        $token = getHeaderToken();
        $userInfo = getJWT($token);

        // 白名单
        $noAuth = [
            'auth/login/index',
            'system/upload/cate',
            'system/upload/list',
            'system/upload/upload',
        ];
        $dynamicNoAuth = array_map(function($v){ return ltrim(strtolower($v), '/'); }, $noAuth);
        if (in_array($route, $dynamicNoAuth)) {
            return $next($request);
        }
        $model = new \app\admin\model\Admin();
        $cacheKey = 'user_permission_' . ($userInfo['id'] ?? 0);
        $permissions = \support\think\Cache::get($cacheKey);
        if ($permissions === null) {
            $permissions = $model->getAllPermissions((int)($userInfo['id'] ?? 0));
            \support\think\Cache::set($cacheKey, $permissions, 7200);
        }
        $authMap = array_map(function($item){
            return strtolower(str_replace(':', '/', trim($item, "/ \t\n\r")));
        }, $permissions ?: []);
        if (in_array('auth/admin/list', $authMap) && !in_array('auth/role/list', $authMap)) {
            $authMap[] = 'auth/role/list';
        }
        if (!in_array('auth/menu/list', $authMap)) {
            $authMap[] = 'auth/menu/list';
        }
        if (!in_array('auth/admin/userinfo', $authMap)) {
            $authMap[] = 'auth/admin/userinfo';
        }
        if ($userInfo['id'] != 1) {
            if (empty($authMap) || !in_array($route, $authMap)) {
                return json([
                    'code' => 403,
                    'msg'  => '无权限访问',
                    'data' => []
                ])->withStatus(403);
            }
        }

        return $next($request);
    }
}